package com.gitee.neuray.security.gateway.strategy;

import com.alibaba.fastjson.JSON;
import com.gitee.neuray.security.admin.authority.PermissionElementDto;
import com.gitee.neuray.security.common.constant.CommonConstants;
import com.gitee.neuray.security.common.exception.BaseException;
import com.gitee.neuray.security.common.msg.BaseResponse;
import com.gitee.neuray.security.common.msg.auth.TokenForbiddenResponse;
import com.gitee.neuray.security.gateway.utils.GateWayResponseUtils;
import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author: zhhongyu
 * @description: 抽象权限校验策略
 * @since: Create in 9:35 2020/3/27
 */
@Slf4j
public abstract class AbstratePermissionStrategy {
    @Value("${zuul.prefix}")
    private String zuulPrefix;


    /**
     * 权限校验方法
     */
    public abstract PermissionElementDto checkout(List<PermissionElementDto> permissionInfos, RequestContext ctx);

    protected String getRequestUri(RequestContext ctx){
        HttpServletRequest request = ctx.getRequest();
        final String requestUri = request.getRequestURI().substring(zuulPrefix.length());
        return requestUri;
    }

    protected void checkargs(List<PermissionElementDto> permissionInfos){
        if(permissionInfos == null || permissionInfos.size() == 0){
            throw new BaseException("该用户的角色在库中无菜单或按钮权限...");
        }
    }

    protected void sendZuulResponseError40301(){
        BaseResponse tokenForbiddenResponse = new TokenForbiddenResponse("请求接口地址没有权限...");
        tokenForbiddenResponse.setStatus(CommonConstants.URL_NOT_PERMISSION);
        GateWayResponseUtils.setFailedRequest(JSON.toJSONString(tokenForbiddenResponse), 200);
    }

    protected void sendZuulResponseError40305(){
        BaseResponse tokenForbiddenResponse = new TokenForbiddenResponse("请求接口方法没有权限...");
        tokenForbiddenResponse.setStatus(CommonConstants.URL_METHOD_NOT_PERMISSION);
        GateWayResponseUtils.setFailedRequest(JSON.toJSONString(tokenForbiddenResponse), 200);
    }

    public void sendZuulResponseError(String msg,int code){
        BaseResponse tokenForbiddenResponse = new TokenForbiddenResponse(msg);
        tokenForbiddenResponse.setStatus(code);
        GateWayResponseUtils.setFailedRequest(JSON.toJSONString(tokenForbiddenResponse), 200);
    }
}
